#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from config import etc
sys.path.append( etc.path_lib )
import FDFSPythonClient

FDFSPythonClient.fdfs_init( etc.path_fdfs_conf, 6)

def upload_file( p_imgid, p_file_path, p_ext_name ) :
    file_obj = open( p_file_path, 'rb')
    try :
        file_content = file_obj.read()
    finally:
        file_obj.close()
    res_upload = FDFSPythonClient.fdfs_upload( file_content, p_ext_name )
    if res_upload[0] == 0 :
        res_raw = res_upload[1]
        tmp = res_raw.split('/',1)
        res_group = int( (tmp[0].split('p'))[1] )
        res_file_id= tmp[1]
        res = {
                'imgid' : p_imgid ,
                'group' : res_group ,
                'path' : res_file_id.split('.',1)[0] ,
                'ext' : p_ext_name ,
                'file_id' : res_file_id ,
            }
        return res
    else :
        return None


def upload_slave_file( p_imgid, p_file_id, p_file_path, p_prefix_name, p_ext_name ) :
    slave_file_obj = open( p_file_path, 'rb')
    try:
        slave_file_content = slave_file_obj.read()
    finally:
        slave_file_obj.close()
    res_upload = FDFSPythonClient.fdfs_slave_upload( slave_file_content, p_ext_name, p_file_id, p_prefix_name )
    if res_upload[0] == 0 :
        res_raw = res_upload[1]
        tmp = res_raw.split('/',1)
        res_group = int( (tmp[0].split('p'))[1] )
        res_file_id= tmp[1]
        res = {
                'imgid' : p_imgid ,
                'group' : res_group ,
                'path' : p_file_id.split('.',1)[0] ,
                'ext' : p_ext_name ,
                'file_id' : res_file_id ,
            }
        return res
    else :
        return None


def download_file_by_group_file_id( p_group, p_file_id, p_file_path ) :
    group = "group" + str(p_group)
    res = FDFSPythonClient.fdfs_download( group, p_file_id )
    if res[0] == 0:
        file = open( p_file_path, 'wb' )
        file.write( res[1] )
        file.close()
        return True
    else :
        return None


def delete_file_by_group_file_id( p_group, p_file_id ) :
    group = "group" + str(p_group)
    res = FDFSPythonClient.fdfs_delete( group, p_file_id )
    if res == 0:
        return True
    else :
        return None


